<!DOCTYPE html>
<html  lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!--360浏览器优先以webkit内核解析-->
    <title>睡眠中心</title>
    <link rel="shortcut icon" href="favicon.ico">
    <link href="../static/css/bootstrap.min.css" th:href="@{/css/bootstrap.min.css}" rel="stylesheet"/>
    <link href="../static/css/font-awesome.min.css" th:href="@{/css/font-awesome.min.css}" rel="stylesheet"/>
    <link href="../static/css/style.min.css" th:href="@{/css/style.min.css}" rel="stylesheet"/>
</head>

<body class="gray-bg">
<div class="wrapper wrapper-content">
    <div class="row">
        <h2 align="center">睡眠报告</h2>
        <div class="panel-body">
            <div class="col-sm-12">
                <div class='panel panel-default'>
                    <div class='panel-heading'>
                        <h4>个人信息</h4>
                    </div>
                    <div class='panel-body'>
                        <label class="col-sm-1 control-label">姓名：</label><div class="col-sm-2"><div class="input-group m-b"><input type="text" disabled="" th:field="*{user.userName}" class="form-control"></div></div>
                        <label class="col-sm-1 control-label">年龄：</label><div class="col-sm-2"><div class="input-group m-b"><input type="text" disabled="" th:field="*{user.age}" class="form-control"></div></div>
                        <label class="col-sm-1 control-label">性别：</label><div class="col-sm-2"><div class="input-group m-b"><input type="text" disabled="" th:value="${sex}" class="form-control"></div></div>
                        <label class="col-sm-1 control-label">身高：</label><div class="col-sm-2"><div class="input-group m-b"><input type="text" disabled="" th:field="*{user.height}" class="form-control"></div></div>
                        <label class="col-sm-1 control-label">体重：</label><div class="col-sm-2"><div class="input-group m-b"><input type="text" disabled="" th:field="*{user.weight}" class="form-control"></div></div>
                        <label class="col-sm-1 control-label">联系方式：</label><div class="col-sm-2"><div class="input-group m-b"><input type="text" disabled="" th:field="*{user.phonenumber}" class="form-control"></div></div>
                        <label class="col-sm-1 control-label">查询日期：</label><div class="col-sm-4"><div class="input-group m-b"><div class="input-group date"><span class="input-group-addon"><i class="fa fa-calendar"></i></span><input type="text" class="form-control" id="query-date" placeholder="yyyy-MM-dd"></div></div></div>
<!--                        <label class="col-sm-1 control-label">病历：</label><div class="col-sm-11"><input type="text" disabled="" th:field="*{user.medical}" class="form-control"></div>-->
                    </div>
                </div>
            </div>
            <div class="col-sm-12">
                <div class='panel panel-default'>
                    <div class='panel-heading'>
                        <h4>睡眠统计</h4>
                    </div>
                    <div class='panel-body'>
                        <label class="col-sm-6 control-label">记录开始时间(hh:mm:ss)：</label><div class="col-sm-6"><div class="input-group m-b"><input type="text" disabled="" id="recordStart" class="form-control"></div></div>
                        <label class="col-sm-6 control-label">记录结束时间(hh:mm:ss)：</label><div class="col-sm-6"><div class="input-group m-b"><input type="text" disabled="" id="recordEnd" class="form-control"></div></div>
                        <label class="col-sm-6 control-label">总记录时间(hh:mm:ss)：</label><div class="col-sm-6"><div class="input-group m-b"><input type="text" disabled="" id="totalRecord" class="form-control"></div></div>
                        <label class="col-sm-6 control-label">总睡眠时间(hh:mm:ss)：</label><div class="col-sm-6"><div class="input-group m-b"><input type="text" disabled="" id="totalSleep" class="form-control"></div></div>
                        <label class="col-sm-6 control-label">睡眠质量：</label><div class="col-sm-6"><div class="input-group m-b"><input type="text" disabled="" id="sleepScale" class="form-control"></div></div>
                        <label class="col-sm-6 control-label">深度睡眠累计时间(hh:mm:ss)：</label><div class="col-sm-6"><div class="input-group m-b"><input type="text" disabled="" id="deepCumulative" class="form-control"></div></div>
                        <label class="col-sm-6 control-label">浅度睡眠累计时间(hh:mm:ss)：</label><div class="col-sm-6"><div class="input-group m-b"><input type="text" disabled="" id="shallowCumulative" class="form-control"></div></div>
                        <label class="col-sm-6 control-label">清醒累计时间(hh:mm:ss)：</label><div class="col-sm-6"><div class="input-group m-b"><input type="text" disabled="" id="soberCumulative" class="form-control"></div></div>
                        <label class="col-sm-6 control-label">深度睡眠百分比：</label><div class="col-sm-6"><div class="input-group m-b"><input type="text" disabled="" id="deepRatio" class="form-control"><span class="input-group-addon">%</span></div></div>
                        <label class="col-sm-6 control-label">浅度睡眠百分比：</label><div class="col-sm-6"><div class="input-group m-b"><input type="text" disabled="" id="shallowRatio" class="form-control"><span class="input-group-addon">%</span></div></div>
                        <label class="col-sm-6 control-label">清醒百分比：</label><div class="col-sm-6"><div class="input-group m-b"><input type="text" disabled="" id="soberRatio" class="form-control"><span class="input-group-addon">%</span></div></div>
                        <input id="deviceCode" type="hidden" disabled="" th:value="*{deviceCode}" class="form-control">
                    </div>
                </div>
            </div>
            <div class="col-sm-12">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4>心率</h4>
                    </div>
                    <div class="panel-body">
                        <div class="echarts" id="heart-rate"></div>
                    </div>
                </div>
            </div>
            <div class="col-sm-12">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4>呼吸率</h4>
                    </div>
                    <div class="panel-body">
                        <div class="echarts" id="respiratory-rate"></div>
                    </div>
                </div>
            </div>
            <div class="col-sm-12">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4>睡眠状态</h4>
                    </div>
                    <div class="panel-body">
                        <div class="echarts" id="sleep-state"></div>
                    </div>
                </div>
            </div>
            <div class="col-sm-12">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4>运动体征</h4>
                    </div>
                    <div class="panel-body">
                        <div class="echarts" id="sports-signs"></div>
                    </div>
                </div>
            </div>
            <div class="col-sm-12">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4>睡眠质量</h4>
                    </div>
                    <div class="panel-body">
                        <div class="echarts" id="sleep-scale"></div>
                    </div>
                </div>
            </div>
            <div class="col-sm-12">
                <div class='panel panel-default'>
                    <div class='panel-heading'>
                        <h4>问卷调查</h4>
                    </div>
                    <div id="answer" class='panel-body'>
                    </div>
                </div>
            </div>
            <div class="col-sm-12">
                <button class="btn btn-success " type="button" th:onclick="exportPdf()"><i class="fa fa-upload"></i>&nbsp;&nbsp;<span class="bold">生成报告</span>
                </button>
            </div>
        </div>
    </div>
</div>
<script th:src="@{/js/jquery.min.js}"></script>
<script th:src="@{/js/bootstrap.min.js}"></script>
<script th:src="@{/ajax/libs/layer/layer.min.js}"></script>
<script th:src="@{/js/sockjs.min.js}"></script>
<script th:src="@{/js/stomp.js}"></script>
<th:block th:include="include :: footer" />
<th:block th:include="include :: datetimepicker-js" />
<script type="text/javascript" src="https://fastly.jsdelivr.net/npm/echarts@5.3.3/dist/echarts.min.js"></script>
<script type="text/javascript">
    var heartUrl;
    var respiratoryUrl;
    var sleepUrl;
    var sportsUrl;
    var scaleUrl;
    var userId = [[${user.userId}]];
    $(function () {
        var heartDataX;
        var heartDataY;
        var respiratoryDataX;
        var respiratoryDataY;
        // var sleepMinX;
        // var sleepTypeItem;
        // var sleepDuration;
        var sleepDataX;
        var sleepDataY;
        var sleepData;
        // var sportsMinX;
        // var sportsTypeItem;
        // var sportsDuration;
        var sportsDataX;
        var sportsDataY;
        var sportsData;
        var scaleDataX;
        var scaleDataY;
        var queryDate;
        var heartBase;
        var respiratoryBase;
        var sleepBase;
        var sportsBase;
        var scaleBase
        layui.use('laydate', function() {
            var laydate = layui.laydate;

            laydate.render({
                elem: '#query-date',
                done:function(value,date){
                    //value, date, endDate点击日期、清空、现在、确定均会触发。回调返回三个参数，分别代表：生成的值、日期时间对象、结束的日期时间对象
                    if(queryDate != value){
                        dateChange(value);
                    }
                    queryDate = value;
                }
            });
        });
        var date = new Date();
        var nowMonth = date.getMonth() + 1;
        if (nowMonth >= 1 && nowMonth <= 9) {
            nowMonth = "0" + nowMonth;
        }
        var strDate = date.getDate();
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        queryDate = date.getFullYear() + "-" + nowMonth + "-" + strDate;
        $('#query-date').val(queryDate);
        dateChange(queryDate);
        $.ajax({
            type: "post",
            dataType: "json",
            data: {
                userId: userId,
                surverId: 1
            },
            url: "/common/queryAnswer",
            success: function (res) {
                if(res.code != 0){
                    $.modal.msgError(res.msg);
                }else{
                    var html = "";
                    var answers = res.data;
                    if(!$.isEmptyObject(answers)){
                        for (let i = 0; i < answers.length; i++) {
                            var answerContent = answers[i].answerContent;
                            if($.isEmptyObject(answerContent)){
                                answerContent = "无"
                            }
                            html += "<label class='col-sm-12 control-label'>" + answers[i].problemOrderNum + "、" + answers[i].problemContent + "</label>" +
                                "<label class='col-sm-12 control-label'>" + answerContent + "</label>";
                        }
                        $('#answer').html(html);
                    }
                }
            }
        });
    });
    function dateChange(date){
        $.ajax({
            type: "post",
            dataType: "json",
            data: {
                userId: userId,
                deviceCode: $('#deviceCode').val(),
                date: date
            },
            url: "/common/getRadarData",
            beforeSend: function(){
                $.modal.loading("数据加载中");
            },
            success: function (res) {
                $.modal.closeLoading();
                if(res.code != 0){
                    $.modal.msgError(res.msg);
                }else{
                    $('#recordStart').val(res.data.recordStart);
                    $('#recordEnd').val(res.data.recordEnd);
                    $('#totalRecord').val(res.data.totalRecord);
                    $('#totalSleep').val(res.data.totalSleep);
                    $('#sleepScale').val(res.data.sleepScale);
                    $('#deepCumulative').val(res.data.deepCumulative);
                    $('#shallowCumulative').val(res.data.shallowCumulative);
                    $('#soberCumulative').val(res.data.soberCumulative);
                    $('#deepRatio').val(res.data.deepRatio);
                    $('#shallowRatio').val(res.data.shallowRatio);
                    $('#soberRatio').val(res.data.soberRatio);
                    heartDataX = res.data.heartDataX;
                    heartDataY = res.data.heartDataY;
                    respiratoryDataX = res.data.respiratoryDataX;
                    respiratoryDataY = res.data.respiratoryDataY;
                    sleepMinX = res.data.sleepMinX;
                    sleepTypeItem = res.data.sleepTypeItem;
                    sleepDuration = res.data.sleepDuration;
                    sportsMinX = res.data.sportsMinX;
                    sportsTypeItem = res.data.sportsTypeItem;
                    sportsDuration = res.data.sportsDuration;
                    sleepDataX = res.data.sleepDataX;
                    sleepDataY = res.data.sleepDataY;
                    sleepData = res.data.sleepData;
                    sportsDataX = res.data.sportsDataX;
                    sportsDataY = res.data.sportsDataY;
                    sportsData = res.data.sportsData;
                    scaleDataX = res.data.scaleDataX;
                    scaleDataY = res.data.scaleDataY;

                    var heartDivId = "heart-rate";
                    var heartTitle = "心率";
                    var heartMinY = 50;
                    heartBase = createEchartLine(heartDivId,heartTitle,heartMinY,heartDataX,heartDataY,'');

                    var respiratoryDivId = "respiratory-rate";
                    var respiratoryTitle = "呼吸率";
                    var respiratoryMinY = 0;
                    respiratoryBase = createEchartLine(respiratoryDivId,respiratoryTitle,respiratoryMinY,respiratoryDataX,respiratoryDataY,'');

                    var sleepDivId = "sleep-state";
                    var sleepTitle = "睡眠状态";
                    var sleepLegend = [{name: '深睡',color: '#3c78d8',selectedMode: false},{name: '浅睡',color: '#4ed984',selectedMode: false},{name: '清醒',color: '#ffc058',selectedMode: false}];
                    // sleepBase = createEchartBar(sleepDivId,sleepTitle,sleepDataX,sleepDataY,sleepData,'');
                    sleepBase = createEchartCustom(sleepDivId,sleepTitle,sleepLegend,sleepDataY,sleepMinX,sleepTypeItem,sleepDuration,'');

                    var sportsDivId = "sports-signs";
                    var sportsTitle = "运动体征";
                    var sportsLegend = [{name: '静止',color: '#3c78d8',selectedMode: false},{name: '活跃',color: '#ffc058',selectedMode: false}];
                    // sportsBase = createEchartBar(sportsDivId,sportsTitle,sportsDataX,sportsDataY,sportsData,'');
                    sportsBase = createEchartCustom(sportsDivId,sportsTitle,sportsLegend,sportsDataY,sportsMinX,sportsTypeItem,sportsDuration,'');

                    var scaleDivId = "sleep-scale";
                    var scaleTitle = "睡眠质量";
                    var scaleMinY = 0;
                    scaleBase = createEchartLine(scaleDivId,scaleTitle,scaleMinY,scaleDataX,scaleDataY,'');
                }
            }
        });
    }
    function getImgUrl(file){
        var url = "";
        $.ajax({
            url: "/common/uploadBase64",
            type: "POST",
            dataType: "json",
            data: {
                file: file
            },
            async: false,
            success: function (res) {
                if (res.code == 0) {
                    url = "https://sunfu.xdkdate.com/" + res.fileName;
                    // url = "https://www.bythealthy.com/sunfu/" + res.fileName;
                    return url;
                } else {
                    $.modal.msgError("上传失败");
                }
            },
        });
        return url;
    }
    function createEchartLine(divId,title,minY,dataX,dataY,unit){
        var lineChart = echarts.init(document.getElementById(divId));
        var lineoption = {
            title: {
                text: title
            },
            animation: false,
            tooltip: {
                trigger: 'axis'
            },
            dataZoom: [
                {
                    show: true,
                    realtime: true,
                    start: 0,
                    end: 100
                },
                {
                    type: 'inside',
                    realtime: true,
                    start: 0,
                    end: 100
                }
            ],
            xAxis: [
                {
                    type: 'category',
                    data: dataX
                }
            ],
            yAxis: [
                {
                    min: minY,
                    type: 'value',
                    axisLabel: {
                        formatter: '{value} ' + unit
                    }
                }
            ],
            series: [
                {
                    name: title,
                    type: 'line',
                    data: dataY
                }
            ]
        };
        lineChart.setOption(lineoption);
        $(window).resize(lineChart.resize);
        return lineChart.getDataURL(lineoption);
    }
    function createEchartCustom(divId,title,legends,dataY,minX,typeItem,duration,unit){
        // let projectItemStartValue = dataXStart.map((item)=>{
        //     return new Date(item).valueOf();
        // });
        // let projectItemDuringValue = dataXEnd.map((item,i)=>{
        //     return new Date(item).valueOf() - projectItemStartValue[i]
        // });
        // let dateMin = minX;
        // let projectItemStartValue = [5000000000000, 90000000000000, 124500000000000, 153000000000000, 137600000000000, 137600000000000];
        // let projectItemDuringValue = [90000000000000, 34500000000000, 39300000000000, 13500000000000, 17800000000000, 28600000000000];
        // let dateMin = 5000000000000;
        // let projectItemStartValue = [1640995200000, 1641168000000, 1641772800000, 1642291200000, 1642550400000];
        // let projectItemDuringValue = [86400000, 777600000, 518400000, 259200000, 86400000];
        // let dateMin = 5000000000000;
        // let projectItemStartValue = [1640995200000, 1641168000000, 1641772800000, 1642291200000, 1642550400000];
        // let projectItemDuringValue = [86400000, 777600000, 518400000, 259200000, 86400000];
        // let dateMin = 1640995200000;
        var barChart = echarts.init(document.getElementById(divId));
        var data = [];
        var startTime = minX;
        var categories = dataY;
        var typeItem = typeItem;
        var duration = duration;
        categories.forEach(function (category, index) {
            var baseTime = startTime;
            for (var i = 0; i < duration.length; i++) {
                data.push({
                    name: typeItem[i].name,
                    value: [typeItem[i].name, baseTime, (baseTime += duration[i]), duration[i]],
                    itemStyle: {
                        normal: {
                            color: typeItem[i].color
                        }
                    }
                });
            }
        });
        var baroption = {
            tooltip: {
                formatter: function (params) {
                    return params.marker + params.name + ': ' + intervalTime(params.value[3]);
                }
            },
            title: {
                text: title
            },
            legend: legends,
            dataZoom: [
                {
                    type: 'slider',
                    filterMode: 'weakFilter',
                    showDataShadow: false,
                    labelFormatter: ''
                },
                {
                    type: 'inside',
                    filterMode: 'weakFilter'
                }
            ],
            xAxis: {
                min: startTime,
                scale: true,
                axisLabel: {
                    color: '#333', // 坐标轴文字颜色
                    formatter: function (val) {
                        let date = new Date(val);
                        let dateLabel = date.getHours()+':'+date.getMinutes()+':'+date.getSeconds();
                        return dateLabel;
                    }
                }
            },
            yAxis: {
                data: categories
            },
            series: [
                {
                    type: 'custom',
                    renderItem: renderItem,
                    itemStyle: {
                        opacity: 0.8
                    },
                    encode: {
                        x: [1, 2],
                        y: 0
                    },
                    data: data
                }
            ]
        };
        barChart.setOption(baroption);
        $(window).resize(barChart.resize);
        return barChart.getDataURL(baroption);
    }
    function createEchartBar(divId,title,dataX,dataY,data,unit){
        var barChart = echarts.init(document.getElementById(divId));
        var baroption = {
            title: {
                text: title
            },
            tooltip: {
                trigger: 'axis'
            },
            dataZoom: [
                {
                    show: true,
                    realtime: true,
                    start: 0,
                    end: 100
                },
                {
                    type: 'inside',
                    realtime: true,
                    start: 0,
                    end: 100
                }
            ],
            xAxis: [
                {
                    type: 'category',
                    data: dataX
                }
            ],
            yAxis: [
                {
                    type: 'category',
                    data: dataY
                }
            ],
            series: [
                {
                    name: title,
                    type: 'line',
                    step: 'start',
                    data: data,
                    lineStyle:{
                        width: 50
                    }
                }
            ]
        };
        barChart.setOption(baroption);
        $(window).resize(barChart.resize);
        return barChart.getDataURL(baroption);
    }
    function exportPdf(){
        heartUrl = getImgUrl(heartBase);
        respiratoryUrl = getImgUrl(respiratoryBase);
        sleepUrl = getImgUrl(sleepBase);
        sportsUrl = getImgUrl(sportsBase);
        scaleUrl = getImgUrl(scaleBase);
        $.ajax({
            type: "post",
            dataType: "json",
            data: {
                userId: userId,
                deviceCode: $('#deviceCode').val(),
                surverId: 1,
                heartUrl: heartUrl,
                respiratoryUrl: respiratoryUrl,
                sleepUrl: sleepUrl,
                sportsUrl: sportsUrl,
                scaleUrl: scaleUrl,
                date: $('#query-date').val()
            },
            url: "/common/exportPdf",
            beforeSend: function(){
                $.modal.loading("数据导出中");
            },
            success: function (res) {
                $.modal.closeLoading();
                if(res.code != 0){
                    $.modal.msgError(res.msg);
                }else{
                    $.modal.msg(res.msg);
                }
            }
        });
    }
    function renderItem(params, api) {
        var categoryIndex = api.value(0);
        var start = api.coord([api.value(1), categoryIndex]);
        var end = api.coord([api.value(2), categoryIndex]);
        var height = api.size([0, 1])[1] * 0.6;
        var rectShape = echarts.graphic.clipRectByRect(
            {
                x: start[0],
                y: start[1] - height / 2,
                width: end[0] - start[0],
                height: height
            },
            {
                x: params.coordSys.x,
                y: params.coordSys.y,
                width: params.coordSys.width,
                height: params.coordSys.height
            }
        );
        return (
            rectShape && {
                type: 'rect',
                transition: ['shape'],
                shape: rectShape,
                style: api.style()
            }
        );
    }
    function intervalTime(duration){
        var days = Math.floor(duration / (24 * 3600 * 1000));
        //计算出小时数
        var leave1 = duration % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
        var hours = Math.floor(leave1 / (3600 * 1000));
        //计算相差分钟数
        var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
        var minutes = Math.floor(leave2 / (60 * 1000));
        //计算相差秒数
        var leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
        var seconds = Math.round(leave3 / 1000);
        return days + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒"
        // return days + "天 " + hours + "小时 ";
    }
</script>
</body>
</html>
